/*
 * @Description: 
 * @Author: Jimmy
 * @Date: 2023-07-23 20:51:42
 * @LastEditTime: 2023-07-26 19:20:52
 * @LastEditors:  
 */
import { Op } from "sequelize"
import Depart from "../model/depart.model"

interface IUser {
    id?: string
    parent_id: string
    name?: string
    status: boolean
    code?:string
}

class DepartService {
    //创建
    async create({ parent_id, name, status, code }: IUser) {
        //写入数据库
        const res = await Depart.create({ parent_id, name, status, code });
        return res.dataValues
    }
    //获取信息
    async getInfo({ id, name }: IUser): Promise<any> {
        let whereOpt = {};
        id && Object.assign(whereOpt, { id })
        name && Object.assign(whereOpt, { name })
        let res = await Depart.findOne({
        //     attributes: ['id', 'parent_id', 'name', 'status', 'code', 'role'],
            where: whereOpt
        });
        return res?.dataValues || null
    }
    //根据id更新信息
    async updateById({ id, name, parent_id, status, code}: IUser) {
        let whereOpt = { id };
        let params = {};
        // username && Object.assign(newUser, { username })
        name && Object.assign(params, { name })
        parent_id && Object.assign(params, { parent_id })
        status && Object.assign(params, { status })
        code && Object.assign(params, { code })
        const res = await Depart.update(params, { where: whereOpt });
        return res[0] > 0 ? true : false
    }
    //根据id删除
    async deleteById(ids) {
        const res = await Depart.destroy({ where: { id:ids } })
        return res > 0 ? true : false;
    }
    //查询列表
    async getList({id='', name='', parent_id='', status='', code='', size=0, page=0 }) {
        let whereOpt = {};
        name && Object.assign(whereOpt, { name:{[Op.like]: `%${name}%`}})
        id && Object.assign(whereOpt, { id })
        parent_id && Object.assign(whereOpt, { parent_id })
        status && Object.assign(whereOpt, { status })
        code && Object.assign(whereOpt, { code })
        let res:any = null
        if(size && page){
            res = await Depart.findAndCountAll({
                where:whereOpt,
                offset: (page - 1) * size,
                limit: size,
                raw: true,
            })
        }else{
            res = await Depart.findAll({
                where:whereOpt,
                raw: true,
            })
        }
        return res || null
    }
}

export default new DepartService